import {isDef} from "../../shared/util";

let depId = 0;

export class Dep {

    /**
     * 当前正在进行数据订阅的 Watcher,
     * Dep 通过 currentWatcher 进行数据依赖收集
     * @type {Watcher}
     */
    static currentWatcher = null;

    constructor() {
        this.id = depId++;
        this.watchers = [];
        this.watcherSet = new Set();
    }

    /**
     * 收集依赖于该数据的 watcher
     * @param {Watcher} watcher
     */
    collect () {
        if (Dep.currentWatcher) {
            const watcher = Dep.currentWatcher;
            if (!this.watcherSet.has(watcher.id)) {
                this.watcherSet.add(watcher.id);
                this.watchers.push(watcher);
                watcher.depend(this);
            }
        }
    }

    notify () {
        for (let i=0; i<this.watchers.length; i++) {
            this.watchers[i].update();
        }
    }

}

Dep.currentWatcher = null;
Dep.currentWatcherStack = [];
export function pushTarget (watcher) {
    if (isDef(Dep.currentWatcher)) {
        Dep.currentWatcherStack.push(watcher);
    }
    Dep.currentWatcher = watcher;
}
export function popTarget () {
    if (Dep.currentWatcherStack.length !== 0) {
        Dep.currentWatcher = Dep.currentWatcherStack.pop();
    }
    return Dep.currentWatcher;
}



